package com.yozinga.fragment;

import java.util.HashMap;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.yozinga.R;
import com.yozinga.fragment.YozingaDialogFragment.ButtonListener;
import com.yozinga.model.BaseModel.OnRequestFinishedCallback;
import com.yozinga.model.CreateAppModel;
import com.yozinga.processor.BusinessTypeProcessor;
import com.yozinga.service.Actions;
import com.yozinga.service.ServiceHelper;
import com.yozinga.util.AddressConversion;
import com.yozinga.util.AlertDialogManager;
import com.yozinga.util.AppData;
import com.yozinga.util.LocationManager;
import com.yozinga.util.SharedData;
import com.yozinga.util.ToolKit;

public class HomePageFragment extends BaseFragment implements OnClickListener/*,ListListener*/,ButtonListener,OnRequestFinishedCallback{

	HomeItemsListener mHomeItemListener;
	private Handler mHandler = new Handler();
	EvalReceiver mEvalReceiver = new EvalReceiver(mHandler);
	TextView tvLoaction,tvChangeLocation;
	HashMap<String,String> mBusinessTypeHashMap;
	ImageView shadedView;
	SharedData mSharedData;
	String mValidAddress;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_homepage, container,false);
	}

	public interface HomeItemsListener{
		public void onCategoryClicked(String categoryName,String id);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			mHomeItemListener = (HomeItemsListener) (activity);
		}catch(ClassCastException castException){
			throw new ClassCastException(activity.toString() + " must implement RestaurantFragment.Callbacks");
		}
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		mSharedData = new  SharedData(getActivity());
		ToolKit.startProgress(getActivity(), R.string.loading);
		LocationManager mMyLocationManager = new LocationManager(getActivity());
		mMyLocationManager.getLocations(mEvalReceiver);
		ServiceHelper serviceHelper = new ServiceHelper(getActivity());
		CreateAppModel createAppModel = new CreateAppModel(getActivity());
		createAppModel.addOnServiceRequestCompletedListener(this);
		String deviceId = Settings.Secure.getString(getActivity().getContentResolver(), 
				Settings.Secure.ANDROID_ID);
		Log.i("Today","Device ID is: "+deviceId+"askfd"+"3E08072BA53852F0");
		createAppModel.getApp(AppData.GET_APP,deviceId,Actions.ACTION_GET_APP);

		((ImageView) getView().findViewById(R.id.ivRestaurant)).setOnClickListener(this);
		((ImageView) getView().findViewById(R.id.ivTravelHotels)).setOnClickListener(this);
		((ImageView) getView().findViewById(R.id.ivEntertainment)).setOnClickListener(this);
		((ImageView) getView().findViewById(R.id.ivShopping)).setOnClickListener(this);
		((ImageView) getView().findViewById(R.id.ivServices)).setOnClickListener(this);
		((ImageView) getView().findViewById(R.id.ivLoyalty)).setOnClickListener(this);



		tvLoaction = (TextView) getView().findViewById(R.id.tvDefaultLocation);
		tvChangeLocation = (TextView)getView().findViewById(R.id.tvChangeLocation);
		tvChangeLocation.setOnClickListener(this);

	}

	@Override
	public void onResume() {
		super.onResume();
		/*if(shadedView!=null){
			//shadedView.setBackgroundColor(Color.WHITE);
			shadedView.setColorFilter(getResources().getColor(
					android.R.color.transparent));
		}*/

	}
	@Override
	public void onClick(View v) {

		//shadedView = (ImageView) v;
		/*((ImageView) v).setBackgroundColor(getResources()
				.getColor(R.color.green));*/
		/*((ImageView) v).setColorFilter(getResources().getColor(
				R.color.green));*/
		if(v.getId() == R.id.ivRestaurant){
			Log.i("Today","HashMap Size is: perticular s"+mBusinessTypeHashMap.get(getActivity().getResources().getString(R.string.restaurant)));
			mHomeItemListener.onCategoryClicked(getActivity().getResources().getString(R.string.restaurant),mBusinessTypeHashMap.get(getActivity().getResources().getString(R.string.restaurant)));
		}
		else if(v.getId() == R.id.ivTravelHotels){
			Log.i("Today","HashMap Size is: perticular s"+mBusinessTypeHashMap.get(getActivity().getResources().getString(R.string.travelandHotels)));
			mHomeItemListener.onCategoryClicked(getActivity().getResources().getString(R.string.travelandHotels),mBusinessTypeHashMap.get(getActivity().getResources().getString(R.string.travelandHotels)));
		}
		else if(v.getId() == R.id.ivEntertainment){
			Log.i("Today","HashMap Size is: perticular s"+mBusinessTypeHashMap.get(getActivity().getResources().getString(R.string.entertainment)));
			mHomeItemListener.onCategoryClicked(getActivity().getResources().getString(R.string.entertainment),mBusinessTypeHashMap.get(getActivity().getResources().getString(R.string.entertainment)));
		}
		else if(v.getId() == R.id.ivShopping){
			Log.i("Today","HashMap Size is: perticular s"+mBusinessTypeHashMap.get(getActivity().getResources().getString(R.string.shopping)));
			mHomeItemListener.onCategoryClicked(getActivity().getResources().getString(R.string.shopping),mBusinessTypeHashMap.get(getActivity().getResources().getString(R.string.shopping)));
		}
		else if(v.getId() == R.id.ivServices){
			Log.i("Today","HashMap Size is: perticular s"+mBusinessTypeHashMap.get(getActivity().getResources().getString(R.string.services)));
			mHomeItemListener.onCategoryClicked(getActivity().getResources().getString(R.string.services),mBusinessTypeHashMap.get(getActivity().getResources().getString(R.string.services)));
		}
		else if(v.getId() == R.id.ivLoyalty){
			Log.i("Today","HashMap Size is: perticular s"+mBusinessTypeHashMap.get(getActivity().getResources().getString(R.string.loyality)));
			mHomeItemListener.onCategoryClicked(getActivity().getResources().getString(R.string.loyality),mBusinessTypeHashMap.get(getActivity().getResources().getString(R.string.loyality)));
		}else if(v.getId() == R.id.tvChangeLocation){
			YozingaDialogFragment dialogFragment = new YozingaDialogFragment(this,"Change Location","Submit",getActivity());
			dialogFragment.show(getFragmentManager(), "fragment_change_Location");
			//ChangeLocationDialogFragment dialogFragment = new ChangeLocationDialogFragment(Double.parseDouble(mSharedData.getLatitude()),Double.parseDouble(mSharedData.getLongitude()),1000,this);
			//dialogFragment.show(getFragmentManager(), "fragment_change_Location");
		}
	}
	/** The ResultReceiver that will receive the result from the Service */
	public class EvalReceiver extends ResultReceiver {
		EvalReceiver(final Handler h) {
			super(h);
		}
		@Override
		public void onReceiveResult(int resultCode, final Bundle resultData) {
			//ToolKit.stopprogess();
			switch (resultCode) {
			case 1:
				String address = resultData.getString("address");
				Log.i("Team","Address is: "+address);
				if(address.equals("Current Location Not Found")){
					AlertDialogManager alertDialogManager = new AlertDialogManager();
					alertDialogManager.showAlertDialog1(getActivity(), "Location Error", "Current Location Not Found", false, "OK");
					//Toast.makeText(getActivity(), "Current Location Not Found", Toast.LENGTH_LONG).show();
				}else{
					tvLoaction.setText(address);
				}
				break;
			case 2:
				if(resultData.getString("address")!=null && resultData.getString("address").equals("Not Valid Address")){
					((TextView)getView().findViewById(R.id.tvDefaultLocation)).setText(mValidAddress);
					AlertDialogManager alertDialogManager = new AlertDialogManager();
					alertDialogManager.showAlertDialog1(getActivity(), "Address Error", "Not Valid Address", false, "OK");
				}else{
					Double latitude = resultData.getDouble("latitude");
					Double longitude = resultData.getDouble("longitude");
					Log.i("Today","HomePageFragment Latitude :"+latitude);
					Log.i("Today","HomePageFragment Logitude :"+longitude);
					mSharedData.setLocationValues(Double.toString(latitude), Double.toString(longitude));
				}
				break;
			default:
				break;
			}

		}
	}

	@Override
	public void onRequestFinished(int resultCode, Bundle payload) {
		Log.i("Today","onRequestFinished"+resultCode+payload.get("action")+Actions.ACTION_GET_APP);
		if(payload.get("action").equals("com.yozinga.GetApp")){
			Log.i("Today","Calling Create APP"+resultCode);
			if(resultCode!=200){
				Log.i("Today","Calling Create APP");
				CreateAppModel createAppModel = new CreateAppModel(getActivity());
				Bundle bundle = new Bundle();
				String deviceId = Settings.Secure.getString(getActivity().getContentResolver(), 
						Settings.Secure.ANDROID_ID);
				Log.i("Today","Device ID is: "+deviceId+"askfd"+"3E08072BA53852F0");
				bundle.putString("DeviceId",deviceId);
				bundle.putString("DeviceType", "Android");
				bundle.putDouble("Latitude", Double.parseDouble("17.441287"));
				bundle.putDouble("Longitude", Double.parseDouble("78.3956767"));
				SharedData sharedData = new SharedData(getActivity());
				if(sharedData.getpushNotification()){
					bundle.putBoolean("PushNotification",sharedData.getpushNotification());
					bundle.putString("StartTime",sharedData.getStartTime());
					bundle.putString("EndTime",sharedData.getEndTime());
				}else{
					bundle.putBoolean("PushNotification",true);
					bundle.putString("StartTime","00:00");
					bundle.putString("EndTime","00:00");
				}		
				createAppModel.createUpdateApp(AppData.CREATE_APP, bundle,Actions.ACTION_CREATE_APP);
			}else{
				Log.i("Today","ACTION_GET_APP Respons is :"+payload.getString("ServiceResponse"));
				CreateAppModel createAppModel = new CreateAppModel(getActivity());
				createAppModel.getListBusinessTypes(AppData.GET_BUSINESSTYPES,Actions.ACTION_GET_BUSINESS_TYPES);
			}
		}
		else if(payload.get("action").equals("com.yozinga.CreateApp")){
			CreateAppModel createAppModel = new CreateAppModel(getActivity());
			createAppModel.getListBusinessTypes(AppData.GET_BUSINESSTYPES,Actions.ACTION_GET_BUSINESS_TYPES);
			Log.i("Today","ACTION_CREATE_APP Respons is :"+payload.getString("ServiceResponse"));
		}else if(payload.get("action").equals("com.yozinga.GetBusinessTypes")){
			ToolKit.stopprogess();
			//LocationManager mMyLocationManager = new LocationManager(getActivity());
			//mMyLocationManager.getLocations(mEvalReceiver);
			String response = payload.getString("ServiceResponse");
			Log.i("Today","GET_BUSINESSTYPES Respons is :"+payload.getString("ServiceResponse"));
			
			BusinessTypeProcessor businessTypeProcess = new BusinessTypeProcessor(mSharedData,"HomeScreen");
			mBusinessTypeHashMap = businessTypeProcess.getBusinessTypes(response);
			Log.i("Today","mBusinessTypeHashMap size is: "+mBusinessTypeHashMap.size());
		}

	}
	
	@Override
	public void locationValue(String locationValue) {
		Log.i("Today","Location Value is:"+locationValue);
		mValidAddress = ((TextView)getView().findViewById(R.id.tvDefaultLocation)).getText().toString();
		((TextView)getView().findViewById(R.id.tvDefaultLocation)).setText(locationValue);
		/*android.view.ViewGroup.LayoutParams layoutParams = tvLoaction.getLayoutParams();
		layoutParams.height = (int) getResources().getDimension(R.dimen.flowSpacing);
		tvLoaction.setLayoutParams(layoutParams);
		tvLoaction.setText(locationValue);*/
		new AddressConversion(locationValue, getActivity(), mEvalReceiver);
	}

	/*@Override
	public void locationValue(String latitude, String longitude, String address) {
		Log.i("Today","latitude is:"+latitude);
		Log.i("Today","Longitude is:"+longitude);
		mSharedData.setLocationValues(latitude, longitude);
		tvLoaction.setText(address);
	}*/

}
